package com.chj.msgdurable;

import com.chj.setmsg.ReplyToProducer;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消息持久化的消费者
 */
public class MsgAttrConsumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("10.200.169.5");
        connectionFactory.setVirtualHost("chj_vhost");
        connectionFactory.setUsername("chj");
        connectionFactory.setPassword("123456");
        // 创建连接
        Connection connection = connectionFactory.newConnection();
        final Channel channel = connection.createChannel();
        // TODO 创建交换器 durable : true
        channel.exchangeDeclare(MsgAttrProducer.EXCHANGE_NAME,"direct",true);
        // 声明一个队列  durable : true
        String queueName = "msgdurable";
        channel.queueDeclare(queueName,true,false,false,null);
        //日志消息级别，作为路由键使用
        String routekey = "chj01";
        channel.queueBind(queueName,MsgAttrProducer.EXCHANGE_NAME,routekey);
        System.out.println("waiting for message........");
        // 声明了一个消费者
        final Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("Received["+envelope.getRoutingKey()+"]"+message);
            }
        };
        // 消费者正式开始在指定队列上消费消息
        channel.basicConsume(queueName,true,consumer);
    }

}
